import NProgress from 'nprogress'

NProgress.configure({ showSpinner: false })

import store from './store'
import router from './router'
import getPageTitle from './utils/get-page-title'
import { getToken } from './utils/auth'

const whiteList = [ '/login' ]

let isLoaded = false
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // TODO: `vue-router@3.0.7`以上版本会报错: Redirected when going from "/login" to "/" via a navigation guard.
  // 逻辑需要再次优化
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (isLoaded) {
        next()
      } else {
        try {
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          router.addRoutes(accessRoutes)
          // eslint-disable-next-line require-atomic-updates
          isLoaded = true
          next({ ...to, replace: true })
        } catch (err) {
          await store.dispatch('user/logout')
          next(`/login?redirect=${ to.path }`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${ to.path }`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
